# if-else的基本语法
x <- 5

if (x > 0) {
  print("x is positive")
} else {
  print("x is non-positive")
}

# else if的使用
x <- 0

if (x > 0) {
  print("x is positive")
} else if (x < 0) {
  print("x is negative")
} else {
  print("x is zero")
}


# ifelse()函数的基本语法
x <- c(-2, -1, 0, 1, 2)
y <- ifelse(x > 0, "Positive", "Non-positive")
print(y)

# 多重条件
x <- c(-2, -1, 0, 1, 2)
y <- ifelse(x > 0, "Positive", ifelse(x == 0, "Zero", "Negative"))
print(y)


# ------------------------------------------
# 准备工作
# ------------------------------------------

setwd("/Users/eimei/Documents/Rdata/")  # 设定工作空间
data <- read.csv("HRdata.csv")  # 读取数据

newdata <- data[c("EmployeeNumber", "Age", "Department", "Attrition", "Education",
                  "EnvironmentSatisfaction", "JobSatisfaction",
                  "MonthlyIncome", "RelationshipSatisfaction")]

temp <- newdata[1:10, ]

# ------------------------------------------
# 任务一
# ------------------------------------------

if(!is.factor(temp$Department)) {
  temp$Department <- as.factor(temp$Department)} else {
  print("已经是因子型")
  }

# ------------------------------------------
# 任务二
# ------------------------------------------

# 与 [ ] 不同，[[ ]] 用于提取数据框的单列时，会返回该列作为向量，而不是数据框的子集。
temp[1]
temp["EmployeeNumber"]
class(temp["EmployeeNumber"])

temp[[1]]
temp[["EmployeeNumber"]]
class(temp[["EmployeeNumber"]])


for(i in names(temp)){
  if(is.character(temp[[i]])) {
    temp[[i]] <- as.factor(temp[[i]])
    cat(i, "已经转换为因子型\n")
    } else {
    cat(i, "的类型是", class(temp[[i]]), "\n")
    }
}

# ------------------------------------------
# 任务三
# ------------------------------------------

ifelse(temp$Age > 35, "大于35", ifelse(temp$Age == 35, "35岁", "小于35"))
